package com.xiaochun.jiankangapp.network

import com.xiaochun.jiankangapp.utils.Constant
import okhttp3.FormBody
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

/**
 * 网络请求访问帮助类
 */
object RequestHelper {
    private val MEDIA_TYPE_JSON: MediaType? = "application/json;charset=utf-8".toMediaTypeOrNull()

    fun addCommonParams(builder: okhttp3.Request.Builder) {
    }

    /**
     * 构建okhttp 需要用到的body,目前是form表单形式
     */
    fun createBody(body: Map<String, Any?>): RequestBody {
        return FormBody.Builder().apply {
            body.forEach {
                add(it.key, it.value?.toString() ?: "")
            }
        }.build()
//        return JsonRequestBody(MEDIA_TYPE_JSON, Gson().toJson(body))
    }


    /**
     * 检查url 是相对地址还是 绝对地址
     */
    fun check(url: String): String {
        if (url.startsWith("http")) {
            return url
        }
        val a = Constant.API_HOST
        if (a?.endsWith("/") == true) {
            return a + url
        } else {
            return "$a/$url"
        }
    }
}